<!--
 * @Author: shiweizhen 787632169@qq.com
 * @Date: 2025-06-24 16:43:06
 * @LastEditors: shiweizhen 787632169@qq.com
 * @LastEditTime: 2025-07-04 17:28:26
 * @Description: 
 * Copyright (c) 2025-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
-->
<template>
  <div class="h-full w-full">
    <div class="w-full h-[120px] border border-solid border-[#dcdfe6] rounded p-2 overflow-hidden overflow-y-auto">
      {{ ' =' + inputValue }}
    </div>
    <div class="h-[48px] mt-2 flex w-full gap-4 items-center">
      <el-input v-model="projectName" placeholder="请输入名称"></el-input>
      <el-button type="primary" @click="getList">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <div class="mt-2 flex w-full gap-4 h-[calc(100%-148px)]">
      <div
        class="w-1/2  h-[calc(100vh-368px)] border border-solid border-[#dcdfe6] rounded p-2 overflow-hidden overflow-y-auto">
        <div class="flex flex-wrap w-full gap-1">
          <div v-for="item in projectList" :key="item.id"
            class="border border-solid border-[#dcdfe6] rounded p-1 cursor-pointer text-ellipsis w-full h-[36px]"
            @click="selectProject(item)">
            {{ item.projectName }}
          </div>
        </div>
      </div>
      <div
        class="flex-1 flex justify-center items-center h-[calc(100vh-368px)] border border-solid border-[#dcdfe6] rounded p-2">
        <el-row :gutter="4" class="w-full">
          <el-col v-for="(item, index) in formulaList" :key="index" :span="item.type === 1 ? 6 : 12"
            @click="selectFormula(item)">
            <div class="text-center border border-solid border-[#dcdfe6] p-1 rounded cursor-pointer mt-1">{{ item.label
            }}
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="fixed bottom-4 right-4">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { FUniver } from '@univerjs/presets';
import { sidebarStore } from '@/store/sidebar'
import { ProjectType } from '@/api/project/types';
import { getMiddleList } from '@/api/project'
import { ID } from 'hbisdt-design';
import { SheetCalType } from '@/api/univer-sheet/types';
import { saveSheetCal } from '@/api/univer-sheet';
const props = defineProps({
  univerAPIInstance: {
    type: Object as () => FUniver,
  }
})
const formulaList = ref([
  { label: '0', value: 'F0', type: 1 },
  { label: '1', value: 'F1', type: 1 },
  { label: '2', value: 'F2', type: 1 },
  { label: '3', value: 'F3', type: 1 },
  { label: '4', value: 'F4', type: 1 },
  { label: '5', value: 'F5', type: 1 },
  { label: '6', value: 'F6', type: 1 },
  { label: '7', value: 'F7', type: 1 },
  { label: '8', value: 'F8', type: 1 },
  { label: '9', value: 'F9', type: 1 },
  { label: '+', value: '+', type: 1 },
  { label: '-', value: '-', type: 1 },
  { label: '/', value: '/', type: 1 },
  { label: '*', value: '*', type: 1 },
  { label: '(', value: '(', type: 1 },
  { label: ')', value: ')', type: 1 },
  { label: 'Backspace', value: 'Backspace', type: 2 },
])
const projectList = ref<ProjectType[]>([])
const projectName = ref('')
const formula = ref<ID[] & string[]>([])
const middleCalIds = ref<ID[]>([])
const univerInstance = props.univerAPIInstance
const useSidebarStore = sidebarStore()
const fWorkbook = univerInstance?.getActiveWorkbook()
const fWorksheet = fWorkbook?.getActiveSheet();
const fWorkCell = fWorkbook?.getActiveCell()
const fSelection = fWorksheet?.getSelection();
const activeRange = fSelection?.getActiveRange();
const inputValue = ref('')
const handleConfirm = async () => {

  const data: SheetCalType = {
    excelRange: activeRange?.getA1Notation()!,
    formula: formula.value.join(','),
    middleCalIds: middleCalIds.value.join(','),
    workbookDataId: fWorkbook?.getId()!,
    workbookSheetId: fWorksheet?.getSheetId()!,
  }
  const res = await saveSheetCal(data)
  fWorkCell?.setValue({ v: res.data || 0, custom: { inputValue: formula.value.join(',') }, s: { bg: { rgb: '#e8f3ff' } } }).setNumberFormat('#,##0')

  useSidebarStore.toggleShow(false)
}
const handleCancel = () => {
  useSidebarStore.toggleShow(false)
}

const selectProject = (item: ProjectType) => {
  formula.value.push(item.id!)

}

const selectFormula = (item: { label: string, value: string, type: number }) => {
  if (item.type === 1) {
    formula.value.push(item.value)

  } else {
    formula.value.pop()

  }
}

const handleReset = () => {
  projectName.value = ''
  getList()
}

const getList = async () => {
  const res = await getMiddleList(projectName.value)
  projectList.value = res.data.records
}

const changeValue = () => {
  const value: string[] = []
  formula.value.forEach((item) => {
    const find = projectList.value.find((i) => i.id === Number(item))
    if (find) {
      value.push(find.projectName)
      middleCalIds.value = [...new Set(middleCalIds.value.concat(find.id!))]
    } else {
      const findFor = formulaList.value.find((i) => i.value === item)
      if (findFor) {
        value.push(findFor.label!)
      }
    }
  })
  return value.join(' ')
}

watch(() => formula.value, () => {
  inputValue.value = changeValue()

}, { deep: true })

onMounted(async () => {
  await getList()
  const customMetaData = fWorkCell?.getCustomMetaData()
  if (customMetaData?.inputValue) {
    formula.value = customMetaData.inputValue.split(',')
    inputValue.value = changeValue()
  }
})
</script>

<style scoped lang="scss">
.text-ellipsis {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>